package drds.plus.executor.function.scalar.string;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

/**
 * <pre>
 * ELT(N,str1,str2,str3,...)
 *
 * ELT() returns the Nth element of the comparativeList of strings: str1 if N = 1, str2 if N = 2, and so on. Returns NULL_KEY if N is less than 1 or greater than the number of argList. ELT() is the complement of FIELD().
 *
 * mysql> SELECT ELT(1, 'ej', 'Heja', 'hej', 'foo');
 *         -> 'ej'
 * mysql> SELECT ELT(4, 'ej', 'Heja', 'hej', 'foo');
 *         -> 'foo'
 * </pre>
 *
 * @author mengshi.sunmengshi 2014年4月11日 下午1:36:05
 * @since 5.1.0
 */
public class Elt extends ScalarFunction {

    public Type getReturnType() {
        return Type.StringType;
    }

    public String[] getFunctionNames() {
        return new String[]{"ELT"};
    }

    public Object compute(ExecuteContext executeContext, Object[] args) {
        if (Utils.isNull(args[0])) {
            return null;
        }

        Integer index = Type.IntegerType.convert(args[0]);

        if (index < 1 || index > args.length - 1) {
            return null;
        }

        Object resEle = args[index];

        if (Utils.isNull(resEle)) {
            return null;
        }

        return Type.StringType.convert(resEle);

    }

}
